#include <string.h>
#include <dirent.h>
#include "esp_err.h"
#include "esp_lvgl_port.h"
#include "music_ui.h"
#include "audio_player.h"
#include "file_iterator.h"
#include "audio.h"
#include "sd_card.h" 
#include "main_ui.h"
#include "ui_setting.h"
#include "pca9557pw.h" 
#include "app_sr.h" 

#define MUSIC_SD_PATH SD_MOUNT_POINT "/music"

// 定义日志标签
static const char *TAG = "music_ui";
static bool is_sd_mounted_ok = false;
// 声明字体
LV_FONT_DECLARE(myFont);
LV_FONT_DECLARE(lv_font_montserrat_14);
static bool is_first_alter_fs = true; //是不是第一次要改变音频

void exit_music_ui(lv_obj_t *root)
{
    switch_to_main_screen(); // 切换到主界面
    if (is_sd_mounted_ok) {
        audio_player_delete(); // 删除音频播放器
        bsp_sdcard_unmount();
        is_sd_mounted_ok = false;
    }
    if (!is_first_alter_fs) {
        //修改过音频参数了
       // renew_codec_fs(); // 重新设置音频参数
        app_sr_init();
        is_first_alter_fs=true;
    }
    /*删除对应的逻辑分析仪界面，防止多次调用，内存泄漏*/
    /*因为功能界面多,而且不常用,所以删除*/
    lv_obj_del(root); //也可以把lv_scr_load_anim的auto_del设置为true
}
    // 手势事件回调函数
    static void event_handler(lv_event_t *e)
{
    lv_event_code_t code = lv_event_get_code(e);

    // 检测手势事件
    if (code == LV_EVENT_GESTURE) {
        lv_indev_t *indev = lv_indev_get_act();
        if (!indev)
            return;

        // 获取手势方向
        lv_dir_t dir = lv_indev_get_gesture_dir(indev);

        // 检测右划或上划手势
        if (dir == LV_DIR_RIGHT || dir == LV_DIR_TOP) {
            exit_music_ui(e->target);
        }
    }
}

/******************** 音乐播放器实现 *********************************************************************************************/

// 播放器配置结构体
static audio_player_config_t player_config = { 0 };
// 系统音量，默认为VOLUME_DEFAULT
static uint8_t g_sys_volume = VOLUME_DEFAULT;
// 文件迭代器实例
static file_iterator_instance_t *file_iterator = NULL;

// UI控件声明
static lv_obj_t *music_list;       // 音乐列表
static lv_obj_t *label_play_pause; // 播放/暂停标签
static lv_obj_t *btn_play_pause;   // 播放/暂停按钮
static lv_obj_t *volume_slider;    // 音量滑动条
static lv_obj_t *music_root;//音乐播放器根控件

// 播放指定序号的音乐
static void
play_index(int index)
{
    ESP_LOGI(TAG, "play_index(%d)", index);

    char filename[128];
    // 从文件迭代器获取完整文件路径
    int retval = file_iterator_get_full_path_from_index(file_iterator, index, filename, sizeof(filename));
    if (retval == 0) {
        ESP_LOGE(TAG, "unable to retrieve filename");
        return;
    }

    // 打开文件
    FILE *fp = fopen(filename, "r");
    if (fp) {
        ESP_LOGI(TAG, "Playing '%s'", filename);
        audio_player_play(fp); // 播放音乐
    } else {
        ESP_LOGE(TAG, "unable to open index %d, filename '%s'", index, filename);
    }
}

// 音频静音设置函数
static esp_err_t _audio_player_mute_fn(AUDIO_PLAYER_MUTE_SETTING setting)
{
    esp_err_t ret = ESP_OK;
    // 设置静音状态
    bsp_codec_mute_set(setting == AUDIO_PLAYER_MUTE ? true : false);
    // 如果不是静音，设置音量
    if (setting == AUDIO_PLAYER_UNMUTE) {
        bsp_codec_volume_set(g_sys_volume, NULL);
    }
    ret = ESP_OK;

    return ret;
}

// 音频数据写入函数
static esp_err_t _audio_player_write_fn(void *audio_buffer, size_t len, size_t *bytes_written, uint32_t timeout_ms)
{
    esp_err_t ret = ESP_OK;

    // 通过I2S写入音频数据
    ret = bsp_i2s_write(audio_buffer, len, bytes_written, timeout_ms);

    return ret;
}
static void user_enter_cb(void)
{
    audio_player_resume(); // 恢复播放
    is_first_alter_fs = false;
}
static void user_exit_cb(void)
{
    exit_music_ui(music_root);// 退出音乐播放器界面
    // lv_event_send(music_root, LV_EVENT_GESTURE, NULL);
}

// 设置采样率函数
static esp_err_t _audio_player_std_clock(uint32_t rate, uint32_t bits_cfg, i2s_slot_mode_t ch)
{
    esp_err_t ret = ESP_OK;
    if (i2s_fs_is_default(rate, bits_cfg, ch)) {
        if (is_first_alter_fs) {
            if (get_voice_control())
            {
                ESP_LOGI(TAG, "_audio_player_std_clock rate:%d ,ch:%d ", rate, ch);
                audio_player_pause(); // 暂停播放
                reminder_voice_clash_ui(rate, bits_cfg, ch, user_enter_cb, user_exit_cb);
                return ret;
            }

        }
    }
    ret = bsp_codec_set_fs(rate, bits_cfg, ch); // 如果播放的音乐固定是16000采样率 这里可以不用打开 如果采样率未知 把这里打开
    return ret;
}

// 音频播放器回调函数
static void _audio_player_callback(audio_player_cb_ctx_t *ctx)
{
    ESP_LOGI(TAG, "ctx->audio_event = %d", ctx->audio_event);
    switch (ctx->audio_event) {
        case AUDIO_PLAYER_CALLBACK_EVENT_IDLE: { // 播放完一首歌
            ESP_LOGI(TAG, "AUDIO_PLAYER_REQUEST_IDLE");
            // 指向下一首歌
            file_iterator_next(file_iterator);
            int index = file_iterator_get_index(file_iterator);
            ESP_LOGI(TAG, "playing index '%d'", index);
            play_index(index);
            // 更新UI显示当前播放的音乐
            lvgl_port_lock(0);
            lv_dropdown_set_selected(music_list, index);
            lvgl_port_unlock();
            break;
        }
        case AUDIO_PLAYER_CALLBACK_EVENT_PLAYING: // 正在播放音乐
            ESP_LOGI(TAG, "AUDIO_PLAYER_REQUEST_PLAY");
            pa_en(1); // 打开音频功放
            break;
        case AUDIO_PLAYER_CALLBACK_EVENT_PAUSE: // 暂停音乐
            ESP_LOGI(TAG, "AUDIO_PLAYER_REQUEST_PAUSE");
            pa_en(0); // 关闭音频功放
            break;
        default:
            break;
    }
}

// MP3播放器初始化
void mp3_player_init(void)
{
    // 获取文件信息
    file_iterator = file_iterator_new(MUSIC_SD_PATH);
    assert(file_iterator != NULL);

    // 初始化音频播放器配置
    player_config.mute_fn = _audio_player_mute_fn; //静音，设置音量
    player_config.write_fn = _audio_player_write_fn;//音频数据写入
    player_config.clk_set_fn = _audio_player_std_clock;//设置采样率
    player_config.priority = 6;
    player_config.coreID = 1;

    // 创建音频播放器实例并注册回调
    ESP_ERROR_CHECK(audio_player_new(player_config));
    ESP_ERROR_CHECK(audio_player_callback_register(_audio_player_callback, NULL));
}

// 按钮样式结构体
typedef struct {
    lv_style_t style_bg;               // 背景样式
    lv_style_t style_focus_no_outline; // 无轮廓焦点样式
} button_style_t;

// 全局按钮样式实例
static button_style_t g_btn_styles;

// 获取按钮样式函数
button_style_t *ui_button_styles(void)
{
    return &g_btn_styles;
}

// 按钮样式初始化
static void ui_button_style_init(void)
{
    /*初始化默认状态样式*/
    lv_style_init(&g_btn_styles.style_focus_no_outline);
    lv_style_set_outline_width(&g_btn_styles.style_focus_no_outline, 0);

    lv_style_init(&g_btn_styles.style_bg);
    lv_style_set_bg_opa(&g_btn_styles.style_bg, LV_OPA_100);
    lv_style_set_bg_color(&g_btn_styles.style_bg, lv_color_make(255, 255, 255));
    lv_style_set_shadow_width(&g_btn_styles.style_bg, 0);
}

// 播放/暂停按钮事件处理函数
static void btn_play_pause_cb(lv_event_t *event)
{
    lv_obj_t *btn = lv_event_get_target(event);
    lv_obj_t *lab = (lv_obj_t *)btn->user_data;

    // 获取当前播放器状态
    audio_player_state_t state = audio_player_get_state();
    printf("state=%d\n", state);
    if (state == AUDIO_PLAYER_STATE_IDLE) { // 空闲状态
        lvgl_port_lock(0);
        lv_label_set_text_static(lab, LV_SYMBOL_PAUSE); // 显示暂停图标
        lvgl_port_unlock();
        int index = file_iterator_get_index(file_iterator);
        ESP_LOGI(TAG, "playing index '%d'", index);
        play_index(index);                          // 播放音乐
    } else if (state == AUDIO_PLAYER_STATE_PAUSE) { // 暂停状态
        lvgl_port_lock(0);
        lv_label_set_text_static(lab, LV_SYMBOL_PAUSE); // 显示暂停图标
        lvgl_port_unlock();
        audio_player_resume();                        // 恢复播放
    } else if (state == AUDIO_PLAYER_STATE_PLAYING) { // 播放状态
        lvgl_port_lock(0);
        lv_label_set_text_static(lab, LV_SYMBOL_PLAY); // 显示播放图标
        lvgl_port_unlock();
        audio_player_pause(); // 暂停播放
    }
}

// 上一首/下一首按钮事件处理函数
static void btn_prev_next_cb(lv_event_t *event)
{
    bool is_next = (bool)event->user_data;

    if (is_next) {
        ESP_LOGI(TAG, "btn next");
        file_iterator_next(file_iterator); // 下一首
    } else {
        ESP_LOGI(TAG, "btn prev");
        file_iterator_prev(file_iterator); // 上一首
    }
    // 更新UI显示当前播放的音乐
    int index = file_iterator_get_index(file_iterator);
    lvgl_port_lock(0);
    lv_dropdown_set_selected(music_list, index);
    lvgl_port_unlock();

    // 根据当前播放器状态处理音乐播放
    audio_player_state_t state = audio_player_get_state();
    printf("prev_next_state=%d\n", state);
    if (state == AUDIO_PLAYER_STATE_IDLE) {
        // 空闲状态不做任何操作
    } else if (state == AUDIO_PLAYER_STATE_PAUSE) { // 暂停状态
        ESP_LOGI(TAG, "playing index '%d'", index);
        play_index(index);                            // 播放音乐
        audio_player_pause();                         // 立即暂停
    } else if (state == AUDIO_PLAYER_STATE_PLAYING) { // 播放状态
        ESP_LOGI(TAG, "playing index '%d'", index);
        play_index(index); // 播放音乐
    }
}

// 音量滑动条事件处理函数
static void volume_slider_cb(lv_event_t *event)
{
    lv_obj_t *slider = lv_event_get_target(event);
    int volume = lv_slider_get_value(slider); // 获取滑动条值
    bsp_codec_volume_set(volume, NULL);       // 设置音量
    g_sys_volume = volume;                    // 保存音量值
    ESP_LOGI(TAG, "volume '%d'", volume);
}

// 音乐列表事件处理函数
static void music_list_cb(lv_event_t *event)
{
    uint16_t index = lv_dropdown_get_selected(music_list); // 获取选中的音乐索引
    ESP_LOGI(TAG, "switching index to '%d'", index);
    file_iterator_set_index(file_iterator, index); // 设置当前播放索引

    // 根据播放器状态处理音乐播放
    audio_player_state_t state = audio_player_get_state();
    if (state == AUDIO_PLAYER_STATE_PAUSE) {          // 暂停状态
        play_index(index);                            // 播放音乐
        audio_player_pause();                         // 立即暂停
    } else if (state == AUDIO_PLAYER_STATE_PLAYING) { // 播放状态
        play_index(index);                            // 播放音乐
    }
}

// 构建文件列表
static void build_file_list(lv_obj_t *music_list)
{
    lvgl_port_lock(0);
    lv_dropdown_clear_options(music_list); // 清空现有选项
    lvgl_port_unlock();

    // 遍历所有文件并添加到下拉列表
    for (size_t i = 0; i < file_iterator->count; i++) {
        const char *file_name = file_iterator_get_name_from_index(file_iterator, i);
        ESP_LOGI(TAG, "add list:file_name=%s", file_name);
        if (NULL != file_name) {
            lvgl_port_lock(0);
            lv_dropdown_add_option(music_list, file_name, i); // 添加音乐名称到列表中
            lvgl_port_unlock();
        }
    }
    lvgl_port_lock(0);
    lv_dropdown_set_selected(music_list, 0); // 选择列表中的第一个
    lvgl_port_unlock();
}

// 播放器界面初始化
lv_obj_t *create_music_ui(void)
{

    lvgl_port_lock(0);
    // 创建根容器（全屏黑色背景）
    music_root = lv_obj_create(NULL);
    if (!music_root)
        return NULL; // 创建失败直接返回
    lv_obj_set_size(music_root, lv_pct(100), lv_pct(100));
    lv_obj_set_style_bg_color(music_root, lv_color_hex(get_screen_color_val()), LV_PART_MAIN);
    lv_obj_add_event_cb(music_root, event_handler, LV_EVENT_GESTURE, NULL); // 添加手势事件
    if (bsp_sdcard_mount() != ESP_OK) {
        ESP_LOGE(TAG, "Music UI: Failed to mount SD card");
        // 显示提示信息
        lv_obj_t *label_voice_err = lv_label_create(music_root);
        lv_label_set_text(label_voice_err, "SD卡挂载失败");
        lv_obj_set_style_text_color(label_voice_err, lv_color_white(), 0);
        lv_obj_set_style_text_font(label_voice_err, &myFont, 0);
        lv_obj_align(label_voice_err, LV_ALIGN_CENTER, 0, -50);
        return music_root;
    }
    is_sd_mounted_ok = true;
    // 初始化mp3播放器
    mp3_player_init();
    ui_button_style_init(); // 初始化按键风格

    /* 创建播放暂停控制按键 */
    btn_play_pause = lv_btn_create(music_root);
    lv_obj_align(btn_play_pause, LV_ALIGN_CENTER, 0, 40);
    lv_obj_set_style_text_font(btn_play_pause, &lv_font_montserrat_14, LV_STATE_ANY);
    lv_obj_set_size(btn_play_pause, 50, 50);
    lv_obj_set_style_radius(btn_play_pause, 25, LV_STATE_DEFAULT);
    lv_obj_add_flag(btn_play_pause, LV_OBJ_FLAG_CHECKABLE);

    // 添加样式
    lv_obj_add_style(btn_play_pause, &ui_button_styles()->style_focus_no_outline, LV_STATE_FOCUS_KEY);
    lv_obj_add_style(btn_play_pause, &ui_button_styles()->style_focus_no_outline, LV_STATE_FOCUSED);

    // 创建播放/暂停标签
    label_play_pause = lv_label_create(btn_play_pause);
    lv_label_set_text_static(label_play_pause, LV_SYMBOL_PLAY);
    lv_obj_set_style_text_font(label_play_pause, &lv_font_montserrat_14, 0);

    lv_obj_center(label_play_pause);

    // 设置用户数据和事件回调
    lv_obj_set_user_data(btn_play_pause, (void *)label_play_pause);
    lv_obj_add_event_cb(btn_play_pause, btn_play_pause_cb, LV_EVENT_VALUE_CHANGED, NULL);

    /* 创建上一首控制按键 */
    lv_obj_t *btn_play_prev = lv_btn_create(music_root);
    lv_obj_set_size(btn_play_prev, 50, 50);
    lv_obj_set_style_radius(btn_play_prev, 25, LV_STATE_DEFAULT);
    lv_obj_clear_flag(btn_play_prev, LV_OBJ_FLAG_CHECKABLE);
    lv_obj_align_to(btn_play_prev, btn_play_pause, LV_ALIGN_OUT_LEFT_MID, -40, 0);

    // 添加样式
    lv_obj_add_style(btn_play_prev, &ui_button_styles()->style_focus_no_outline, LV_STATE_FOCUS_KEY);
    lv_obj_add_style(btn_play_prev, &ui_button_styles()->style_focus_no_outline, LV_STATE_FOCUSED);
    lv_obj_add_style(btn_play_prev, &ui_button_styles()->style_bg, LV_STATE_FOCUS_KEY);
    lv_obj_add_style(btn_play_prev, &ui_button_styles()->style_bg, LV_STATE_FOCUSED);
    lv_obj_add_style(btn_play_prev, &ui_button_styles()->style_bg, LV_STATE_DEFAULT);

    // 创建上一首标签
    lv_obj_t *label_prev = lv_label_create(btn_play_prev);
    lv_label_set_text_static(label_prev, LV_SYMBOL_PREV);
    lv_obj_set_style_text_font(label_prev, &lv_font_montserrat_14, LV_STATE_DEFAULT);
    lv_obj_set_style_text_color(label_prev, lv_color_make(0, 0, 0), LV_STATE_DEFAULT);
    lv_obj_center(label_prev);
    lv_obj_set_user_data(btn_play_prev, (void *)label_prev);
    lv_obj_add_event_cb(btn_play_prev, btn_prev_next_cb, LV_EVENT_CLICKED, (void *)false);

    /* 创建下一首控制按键 */
    lv_obj_t *btn_play_next = lv_btn_create(music_root);
    lv_obj_set_size(btn_play_next, 50, 50);
    lv_obj_set_style_radius(btn_play_next, 25, LV_STATE_DEFAULT);
    lv_obj_clear_flag(btn_play_next, LV_OBJ_FLAG_CHECKABLE);
    lv_obj_align_to(btn_play_next, btn_play_pause, LV_ALIGN_OUT_RIGHT_MID, 40, 0);

    // 添加样式
    lv_obj_add_style(btn_play_next, &ui_button_styles()->style_focus_no_outline, LV_STATE_FOCUS_KEY);
    lv_obj_add_style(btn_play_next, &ui_button_styles()->style_focus_no_outline, LV_STATE_FOCUSED);
    lv_obj_add_style(btn_play_next, &ui_button_styles()->style_bg, LV_STATE_FOCUS_KEY);
    lv_obj_add_style(btn_play_next, &ui_button_styles()->style_bg, LV_STATE_FOCUSED);
    lv_obj_add_style(btn_play_next, &ui_button_styles()->style_bg, LV_STATE_DEFAULT);

    // 创建下一首标签
    lv_obj_t *label_next = lv_label_create(btn_play_next);
    lv_label_set_text_static(label_next, LV_SYMBOL_NEXT);
    lv_obj_set_style_text_font(label_next, &lv_font_montserrat_14, LV_STATE_DEFAULT);
    lv_obj_set_style_text_color(label_next, lv_color_make(0, 0, 0), LV_STATE_DEFAULT);
    lv_obj_center(label_next);
    lv_obj_set_user_data(btn_play_next, (void *)label_next);
    lv_obj_add_event_cb(btn_play_next, btn_prev_next_cb, LV_EVENT_CLICKED, (void *)true);

    /* 创建声音调节滑动条 */
    volume_slider = lv_slider_create(music_root);
    lv_obj_set_size(volume_slider, 200, 10);
    lv_obj_set_ext_click_area(volume_slider, 15);
    lv_obj_align(volume_slider, LV_ALIGN_BOTTOM_MID, 0, -20);
    lv_slider_set_range(volume_slider, 0, 100);
    lv_slider_set_value(volume_slider, g_sys_volume, LV_ANIM_ON);
    lv_obj_add_event_cb(volume_slider, volume_slider_cb, LV_EVENT_VALUE_CHANGED, NULL);

    // 创建音量图标
    lv_obj_t *lab_vol_min = lv_label_create(music_root);
    lv_label_set_text_static(lab_vol_min, LV_SYMBOL_VOLUME_MID);
    lv_obj_set_style_text_font(lab_vol_min, &lv_font_montserrat_14, LV_STATE_DEFAULT);
    lv_obj_align_to(lab_vol_min, volume_slider, LV_ALIGN_OUT_LEFT_MID, -10, 0);

    lv_obj_t *lab_vol_max = lv_label_create(music_root);
    lv_label_set_text_static(lab_vol_max, LV_SYMBOL_VOLUME_MAX);
    lv_obj_set_style_text_font(lab_vol_max, &lv_font_montserrat_14, LV_STATE_DEFAULT);
    lv_obj_align_to(lab_vol_max, volume_slider, LV_ALIGN_OUT_RIGHT_MID, 10, 0);

    /* 创建音乐列表 */
    music_list = lv_dropdown_create(music_root);
    lv_dropdown_clear_options(music_list);
    lv_dropdown_set_options_static(music_list, "扫描中...");
    lv_obj_set_style_text_font(music_list, &myFont, LV_STATE_ANY);
    lv_obj_set_width(music_list, 200);
    lv_obj_align(music_list, LV_ALIGN_TOP_MID, 0, 60);
    lv_obj_add_event_cb(music_list, music_list_cb, LV_EVENT_VALUE_CHANGED, NULL);

    // 构建文件列表
    build_file_list(music_list);

    lvgl_port_unlock();

    return music_root;
}